import React from 'react'
import { View, Image } from '@tarojs/components'
import { AtActivityIndicator } from 'taro-ui'
import Taro from '@tarojs/taro'
import './index.scss'
import { DeviceMode } from '../../serverless/deviceMode'

export default class Index extends React.Component {

  state = {
    deviceMode: [] as DeviceMode[],
    loading: true,
    groupId: ''
  }

  async componentWillMount() {
    try {
      const b = Taro.getCurrentInstance();
      if (b.router) {
        const { groupId } = b.router.params
        this.setState({ groupId: groupId })
      } else
        throw new Error('页面传入信息不全');
      const a = await DeviceMode.GetDeviceMode();
      console.log(a);
      this.setState({
        deviceMode: a,
        loading: false
      })
    } catch (error) {
      Taro.showModal({
        title: '提示',
        content: '加载设备列表失败',
        showCancel: false
      })
    }
  }

  handleClick(key: string, value: any) {
    this.setState({
      [key]: value
    })
  }

  deviceListInfoRow(key: string, value: string, className: string = '') {
    return <View className={`at-row device-list-info ${className} `}>
      <View className='at-col at-col-4 key'>{key}</View>
      <View className='at-col at-col-8 value view-white-space'>{value}</View>
    </View>
  }


  render() {
    const { deviceMode, loading, groupId } = this.state

    /** 渲染列表 */
    const arr = deviceMode.map((x, i) => {
      return <View className='at-row deviceMode' key={i}>
        <View className='at-col at-col-12'>
          <View className='border' hoverClass='hover' hoverStartTime={20} hoverStayTime={70} onClick={() => {
            Taro.navigateTo({
              url: x.getBindPath(groupId)
            })
          }}>
            <View className='at-row max-height'>
              {/* 输出图片 */}
              <View className='at-col at-col-3 center-horizontally'>
                <Image className='image' src={x.iconPath} />
              </View>
              {/* 输出信息 */}
              <View className='at-col at-col-8'>
                {this.deviceListInfoRow('设备名称：', x.name)}
                {this.deviceListInfoRow('设备型号：', x.mode)}
                {this.deviceListInfoRow('设备说明：', x.explain, 'explain')}
              </View>
              {/* 标识 */}
              <View className='at-col at-col-1 center-horizontally'>
                <View className='at-icon at-icon-chevron-right animated fadeInLeft infinite'></View>
              </View>
            </View>
          </View>
        </View>
      </View>
    })

    return (
      <View className='index guide'>
        {/* 输出渲染的设备列表 */}
        {loading === true && <View className='loading center-horizontally'>
          <AtActivityIndicator content='加载中...'></AtActivityIndicator>
        </View>}
        {loading === false && <View>
          {arr}
        </View>}
      </View>
    )
  }
}
